package com.elitel.frame.business.service.utils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.base.service.BaseFieldaddonsService;
import com.elitel.frame.main.entity.CfgExtmaster;
import com.elitel.frame.main.entity.ext.BaseFieldaddonsExt;

// Only for help construct sql statement
public final class SQLConstructHelper{
	public static String handleViewWhereCondition(BaseFieldaddonsService baseFieldaddonsService, String dtConfigId,String whereContent) {
		// if is view query condition, need convert field to tableName.columnName (because of existed same field in different table)
		// 1. split by and , to String[] conditionElements , each element format fieldName symbol fieldValue , which symbol contains ('=' , '>=', and so on)
		String[] conditionElements = whereContent.split(" and ");
		String symbol = "=";

		List<BaseFieldaddonsExt> baseFieldAddonsList =  baseFieldaddonsService.selectExtendFieldaddonsList(dtConfigId);
		Map<String, List<BaseFieldaddonsExt>> baseFieldAddonsListMap = baseFieldAddonsList.stream().collect(Collectors.groupingBy(BaseFieldaddonsExt :: getFieldname));
        if(XCommonUtils.isEmpty(baseFieldAddonsListMap))
            return whereContent;

		StringBuilder whereConditionBuilder = new StringBuilder();
		StringBuilder conditionBuilder = new StringBuilder();
		for(String element : conditionElements){
			if(XCommonUtils.isEmpty(element))
				continue;

            symbol = findConditionSymbol(element);
			// 2. split by symbol (by using regular expression, now only support equals symbol),
			String [] keyAndValue = element.split(symbol);
			if(keyAndValue == null || keyAndValue.length < 2)
				continue;

			String fieldName = keyAndValue[0].trim();
			String fieldValue = keyAndValue[1];

			// 3. now match fieldName from baseFieldAddonsExt(contain fieldName), get baseFieldAddonsExt, then convert key into tableName.columnName
			BaseFieldaddonsExt baseFieldaddonsExt = baseFieldAddonsListMap.get(fieldName).get(0);
			String tableName = baseFieldaddonsExt.getAltername();

			// 4. concat condition , which format is “ and key symbol value”
			conditionBuilder.append(" and ").append(tableName).append(".").append(fieldName).append(symbol).append(fieldValue).append(" ");

			whereConditionBuilder.append(conditionBuilder.toString());
			conditionBuilder.setLength(0);
		}

		return whereConditionBuilder.toString();
	}

    private static String findConditionSymbol(String condition){
        return XCommonUtils.findConditionSymbol(condition);
    }



}
